var initialPath = projectName+"/page/404NotFound.jsp";
var tabTitle ="Random Name";
var tabTemplate = "<li><a href='#{href}' style='font-size:14px;padding:4px 7px 5px 7px;outline:none;'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
var tabCounter = 0;
var tabs;
var defaultFrameSize = 1;

$(function(){
    tabs = $( "#pageTabs" ).tabs();//初始化Tab页面
	condition = $("#sel_DeviceInfo").val();
	initialMenus();//生成下拉菜单
	initialTabPages();//初始化主页
	initialAlarmInfoTable();
	initialDialog();
	initResizableElement();
//	JSalarmDwr.alarmMessagePush();//启动DWR告警轮询
});

function initialMenus(){
    $('#jsddm li').hover(
        function () {
        //show its submenu
            $('ul', this).stop().slideDown(300);
        }, 
        function () {
        //hide its submenu
            $('ul', this).stop().slideUp(100);          
        }
    );
}

function initialTabPages(){
    
    $( "#pageTabs" ).tabs({
      beforeLoad: function( event, ui ) {
        ui.jqXHR.error(function() {
          ui.panel.html(
            "Couldn't load this tab. We'll try to fix this as soon as possible. ");
        });
      }
    });
    
    // close icon: removing the tab on click
    tabs.delegate( "span.ui-icon-close", "click", function() {
      var panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
      $( "#" + panelId ).remove();
      tabCounter--;
      tabs.tabs( "refresh" );
    });
 
    tabs.bind( "keyup", function( event ) {
      if ( event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE ) {
        var panelId = tabs.find( ".ui-tabs-active" ).remove().attr( "aria-controls" );
        $( "#" + panelId ).remove();
        tabCounter--;
        tabs.tabs( "refresh" );
      }
    });
}

/* 
 * @Author Engels Hua
 * @Param  element:传入参数，element.innerHTML是Tab标题。
 * @Param  path:页面路径。
 */
function addTab(element,path){
    tabTitle = element.innerHTML;
    var tabList = $(".ui-state-default").children(".ui-tabs-anchor");
    var sameTabFlag = true;
	tabList.each(function(i){
		if(tabTitle===this.innerHTML){
			alert("该页面已经打开！");
			sameTabFlag = false;
		}
	});
	if(sameTabFlag){
		initialPath = path;
	    var  li = $( tabTemplate.replace( /#\{href\}/g, initialPath ).replace( /#\{label\}/g, tabTitle ) );
	    tabs.find( ".ui-tabs-nav" ).append( li );
	    tabs.tabs( "refresh" );
	    tabCounter++;
	    tabs.tabs( { active: tabCounter } );
	}
}

/*
 * @Author Engels Hua
 * @Param  tabName为指定的要关闭的Tab页面标题名;
 *         如果只是简单的想关闭当前打开并选中的Tab页面,也可将tabName赋值为"active_tab"
 * 
 */

function closeTab(tabName){
	if(tabName==="active_tab"){
		var tabLi = $(".ui-tabs-active");
		var divId = tabLi.attr("aria-controls");
		$("#"+divId).remove();
		$(".ui-tabs-active").remove();
	}else{
		var tabList = $(".ui-state-default").children(".ui-tabs-anchor");
		tabList.each(function(i){
			if(tabName===this.innerHTML){
				//var parentElement = this.parentNode
				var divId = this.parentNode.getAttribute("aria-controls");
				var divElement = document.getElementById(divId);
				divElement.parentNode.removeChild(divElement);
				this.parentNode.parentNode.removeChild(this.parentNode);
			}
		});
	}
	tabs.tabs( "refresh" );
    tabCounter--;
    tabs.tabs( { active: tabCounter } );
}

function initialAlarmInfoTable(){
	var alarmInfoTable = document.getElementById("bottomZone");
	var tableHeight = alarmInfoTable.offsetHeight-55;
	var tableWidth = alarmInfoTable.offsetWidth+18;
	jQuery("#alarmInfoTable").jqGrid({
		height: tableHeight,
		width:tableWidth,
		url:contextPath+'/alarminfo/getAllCurrentAlarmLog.action',
		datatype: "json",
		colNames:['id',"告警名称","设备名称","最新告警时间","告警等级","告警次数","站点编号","设备编号","首次告警时间"],
	   	colModel:[
	   	      {name:"alarmLogId",index:"alarmLogId",hidden:true,editable:true,key:true},
	   	      
	   	      {name:'alarmName',index:'alarmName', width:50,align:"center"},
	   	      
	   	      {name:'rptName',index:'equipmentName', width:50, align:"center"},
	   	      
	   	      {name:'lastAlarmTime',index:'alarmLogId', width:60, align:"center"},
	   		
	   		  {name:'alarmLevelName',index:'alarmLevelName', width:50,align:"center"},
	   		  
	   		  {name:'alarmTimes',index:'alarmTimes', width:40,align:"center"},
	   		  
	   		  {name:'rptNo',index:'rptNo', width:60,align:"center"},
	   		  
	   		  {name:'subNo',index:'subNo', width:50,align:"center"},
	   		  
	   		  {name:'alarmTime',index:'alarmLogId', width:60, align:"center"},
	   	],
	   	jsonReader : {  
	   	    root: "root",   // json中代表实际模型数据的入口   
	   	    repeatitems: false, // 如果设为false，则jqGrid在解析json时，会根据name来搜索对应的数据元素（即可以json中元素可以不按顺序）；而所使用的name是来自于colModel中的name设定。   
	   	} ,
	   	
	   	hidegrid: false,
	    loadtext: "Loading...",
	    scrollrows:true,
	    rownumbers: true,
	    sortname: 'id',
	    //shrinkToFit:false,
	    caption:"<span id='alarmTableTitle' class='alarm-table-title'>实时告警信息栏</span>"+
	    	"<span id='collapse_Table' class='ui-icon ui-icon-circle-triangle-s' onclick='clickCollapseTable();'></span>"
	});
	
	/*
	function expertSuggestion(cellvalue, options, rowObject){
		return "<a href='#'>专家库意见</a>";
	}
	
	function clearAlarmInfo(cellvalue, options, rowObject){
		return "<a href='#'>清除告警</a>";
	}*/
}

function clickCollapseTable(){
	var tableTitleBar = $("#collapse_Table").parent("span").parent("div.ui-jqgrid-titlebar");
	$("#collapse_Table").toggleClass(function(index,className){
		if(className==="ui-icon ui-icon-circle-triangle-s"){
			$("#collapse_Table").removeClass("ui-icon-circle-triangle-s");
			tableTitleBar.siblings().toggle("normal");
			$("#middleZone").animate({height:"88%"},"normal");
			$("#bottomZone").animate({height:"4%"},"normal");
			return "ui-icon ui-icon-circle-triangle-n";
		}
		if(className==="ui-icon ui-icon-circle-triangle-n"){
			$("#collapse_Table").removeClass("ui-icon-circle-triangle-n");
			tableTitleBar.siblings().toggle("normal");
			$("#middleZone").animate({height:"65%"},"normal");
			$("#bottomZone").animate({height:"27%"},"normal");
			return "ui-icon ui-icon-circle-triangle-s";
		}
	},true);
}

function initialDialog(){
	$( "#messagePushTest" ).dialog({
	      autoOpen: false,
	      position:{my: "left bottom", at: "left bottom", of: $("#entireFrame") },
	      show: {
	        effect: "drop",
	        duration: 1000
	      },
	      hide: {
	        effect: "blind",
	        duration: 500
	      },
//	      open: function( event, ui ) {
//	    	  
//	      },
	      width:350,
	      heigth:140
	});
	
	$( "#accountInfoWindow" ).dialog({
	      autoOpen: false,
	      width:350,
	      heigth:140,
	      position:{my: "center bottom", at: "center center", of: $("#entireFrame") },
	      show: {
	        effect: "drop",
	        duration: 1000
	      },
	      hide: {
	        effect: "blind",
	        duration: 500
	      }
	});
	
	$("#closeInfoWin").button().click(function(){
		$( "#accountInfoWindow" ).dialog("close");
	});
	$("#quitSystemButton").button();
	
	alarmInfoDisplayWindow = $( "#messagePushTest" );
}

function openDialog(displayInfo){
	alarmInfoDisplayWindow.html("");
	alarmInfoDisplayWindow.html(displayInfo);
	if(alarmInfoDisplayWindow.dialog("isOpen")){
		alarmInfoDisplayWindow.dialog("close");
		alarmInfoDisplayWindow.dialog("open");
	}else{
		alarmInfoDisplayWindow.dialog( "open" );
	}
}
function initResizableElement(){
	defaultFrameSize = getSourceSize();
	var test = defaultFrameSize.rightZone;
	$("#mainZone").resizable({
		animate:true,
		maxHeight:defaultFrameSize.rightZone.height,
		minHeight:0,
		minWidth :defaultFrameSize.rightZone.width,
		maxWidth :defaultFrameSize.rightZone.width,
		//containment:"#rightZone"
	});
	$("#bottomZone").resizable({
		animate:true,
		maxHeight:defaultFrameSize.rightZone.height,
		minHeight:0,
		minWidth :defaultFrameSize.rightZone.width,
		maxWidth :defaultFrameSize.rightZone.width,
		containment:"#rightZone"
	});
}

/*
function dwrCallBack(data){
	if(null!=data&&data instanceof Object){
		jQuery("#alarmInfoTable").jqGrid('addRowData',data.alarmLogId,data);
	}
}
*/